package com.wt.controller;

import com.alibaba.fastjson.JSONObject;
import com.wt.entity.Travel;
import com.wt.service.TravelService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/TravelServlet")
public class TravelServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String search = request.getParameter("search");
        if (search == null){
             PrintWriter out = response.getWriter();
             String err = "{\"error\":\"errorParameter\"}";
             out.write(err);
             return;
        }
        TravelService travelService = new TravelService();
        try {
            List<Travel> travels = travelService.searchTravel(search);
            //查询结果为空
            if (travels == null){
                PrintWriter out = response.getWriter();
                String err = "{\"error\":\"null\"}";
                out.write(err);
                return;
            }
            PrintWriter out = response.getWriter();
            //            使用fastjson将对象集合转化为json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",travels);
            out.write(jsonObject.toString());
            out.flush();

//            //封装json
//            StringBuilder jsonData = new StringBuilder();
//            jsonData.append("[");
//            for (int i = 0; i < travels.size(); i++){
//                jsonData.append("{\"area_name\":\"").append(travels.get(i).getAreaName()).append("\",");
//                jsonData.append("\"area_prairies\":\"").append(travels.get(i).getAreaPrairies()).append("\",");
//                jsonData.append("\"scenic_name\":\"").append(travels.get(i).getScenicName()).append("\",");
//                jsonData.append("\"scenic_depict\":\"").append(travels.get(i).getScenicDepict()).append("\",");
//                jsonData.append("\"scenic_image\":\"").append(travels.get(i).getScenicImage()).append("\",");
//                if (i == travels.size() - 1){
//                    jsonData.append("\"scenic_score\":\"").append(travels.get(i).getScenicScore()).append("\"}");
//                } else {
//                    jsonData.append("\"scenic_score\":\"").append(travels.get(i).getScenicScore()).append("\"},");
//                }
//            }
//            jsonData.append("]");
//            out.write(jsonData.toString());
//            out.flush();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
